﻿using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Log
{
    public class LogHelper
    {
        public static ILog loginfo;
        public static ILog logerror;


        static LogHelper()
        {
            var repository = LogManager.CreateRepository("NETCoreRepository");
            //log4net从log4net.config文件中读取配置信息
            XmlConfigurator.Configure(repository, new FileInfo("Log4net.config"));

            loginfo = LogManager.GetLogger(repository.Name, "loginfo");
            logerror = LogManager.GetLogger(repository.Name, "logerror");
        }


        public static void DeleteLogDirectory(string path)
        {
            string dataPath = Path.Combine(Environment.CurrentDirectory, path);

            if (!Directory.Exists(dataPath))
            {
                return;
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(dataPath);
            DirectoryInfo[] fileInfos = directoryInfo.GetDirectories();

            Array.Sort(fileInfos, (x, y) =>
            {
                return y.CreationTime.CompareTo(x.CreationTime);
            });

            foreach (var fileInfo in fileInfos)
            {
                string fileName = fileInfo.Name;
                DateTime createFileDate = DateTime.Parse(fileName);

                TimeSpan sp = DateTime.Now.Subtract(createFileDate);
                int days = sp.Days;

                int createMonth = int.Parse(fileInfo.Name.Split('-')[1]);

                if (days >= 30)
                {
                    DirectoryInfo info = new DirectoryInfo(fileInfo.FullName);
                    info.Delete(true);
                }
            }
        }

        /// <summary>
        /// 系统日志，一般日志
        /// </summary>
        /// <param name="info"></param>
        public static string WriteLog(string msg)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(msg);
            }
            return msg;
        }

        /// <summary>
        /// 系统日志，异常日志
        /// </summary>
        /// <param name="info"></param>
        public static string WriteLog(string msg, Exception ex)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(msg, ex);
            }
            return msg;
        }
    }
}
